<template>
  <div class="xwchat-login-btn">
    <button class="icon-btn" @click="openLogin" title="登录">
      <el-icon><UserFilled /></el-icon>
    </button>
  </div>
  <div class="app">
    <div class="wechat-container">
      <!-- 左侧导航栏（简化） -->
      <div class="sidebar">
        <div class="nav-item active">
          <el-avatar shape="square" class="fas" :src="myAvatar"></el-avatar>
        </div>
        <div class="nav-item active" @click="refreshMessages">
          <el-icon><Refresh /></el-icon>
        </div>
        <div class="nav-item active" @click="addUserClick">
          <el-icon><ZoomIn /></el-icon>
        </div>
        <div class="nav-item active" @click="delUserClick">
          <el-icon><ZoomOut /></el-icon>
        </div>
        <div class="nav-item active" @click="settingClick">
          <el-icon><Setting /></el-icon>
        </div>

        <div class="set-item">
          <div class="nav-item">
            <i class="fas el-icon-setting"></i>
          </div>
        </div>
      </div>

      <!-- 左侧会话列表 -->
      <div class="contact-panel">
        <div class="search-bar">
          <div class="search-box">
            <i class="fas el-icon-user"></i>
            <input v-model="state.userIdInput" type="number" placeholder="当前用户ID" />
          </div>
          <div class="search-add">
            <el-tag color="#e6e6e6" type="info" @click="applyUserId"
              ><i class="fas el-icon-check"></i>+</el-tag
            >
          </div>
        </div>

        <div class="contact-list">
          <div
            :class="{ active: session.id === state.activeSessionId }"
            v-for="session in state.sessions"
            :key="session.id"
            @click="selectSession(session)"
          >
            <div class="contact-item" v-if="session.sessionType === 'single'">
              <div class="contact-avatar">
                <el-avatar
                  shape="square"
                  class="fas"
                  :src="session.sysUserVo?.avatarUrl ?? userAvatar"
                />
              </div>
              <div class="contact-info">
                <div class="contact-name">
                  {{ session.sysUserVo?.account || '单聊' }}
                </div>
                <div class="contact-preview">
                  {{ session.lastMessageId ? '消息ID ' + session.lastMessageId : '暂无消息' }}
                </div>
              </div>
              <div class="contact-meta">
                <div class="contact-time">{{ formatTime(session.lastMessageAt) }}</div>
                <div class="unread-count">{{ 0 }}</div>
              </div>
            </div>

            <div class="contact-item" v-else>
              <div class="contact-avatar">
                <el-avatar
                  shape="square"
                  class="fas"
                  :src="session.sessionType === 'group' ? groupAvatar : userAvatar"
                />
              </div>
              <div class="contact-info">
                <div class="contact-name">
                  {{ session.name || '群聊' }}
                </div>
                <div class="contact-preview">
                  {{ session.lastMessageId ? '消息ID ' + session.lastMessageId : '暂无消息' }}
                </div>
              </div>
              <div class="contact-meta">
                <div class="contact-time">{{ formatTime(session.lastMessageAt) }}</div>
                <div class="unread-count">{{ 0 }}</div>
              </div>
            </div>
          </div>

          <div v-if="!state.sessions.length" class="empty-tip">
            设置用户ID后点击右侧对勾加载会话
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-container">
        <div class="chat-header">
          <div class="chat-title">
            <div class="chat-avatar">
              <el-avatar shape="square" class="fas" :src="headerAvatar"></el-avatar>
            </div>
            <div>
              <div class="chat-name">{{ headerTitle }}</div>
              <div class="chat-status" v-if="state.activeSessionId">
                会话ID：{{ state.activeSessionId }}
              </div>
            </div>
          </div>
          <div class="chat-actions">
            <div class="nav-item" v-if="loginId != 0">
              <el-icon color="#00C129"><Sunny /></el-icon>
              <div class="chat-online">在线</div>
            </div>
            <div class="nav-item" v-else-if="loginId === 0">
              <el-icon><Moon /></el-icon>
              <div class="chat-online">离线</div>
            </div>
          </div>
        </div>

        <div class="chat-messages" ref="chatMessagesRef">
          <div v-if="state.activeSessionId && !state.messages.length" class="timestamp">
            暂无消息
          </div>
          <div
            v-for="msg in state.messages"
            :key="msg.id || msg.createdAt + Math.random()"
            class="message"
            :class="msg.senderId === state.currentUserId ? 'self' : 'other'"
          >
            <div class="message-avatar">
              <el-avatar
                shape="square"
                class="fas"
                :src="msg.senderId === state.currentUserId ? selfAvatar : otherAvatar"
              ></el-avatar>
            </div>
            <div class="message-content">
              <div class="message-bubble">
                <template v-if="msg.msgType === 'text'">
                  {{ msg.content }}
                </template>
                <template v-else-if="msg.msgType === 'image'">
                  <img :src="msg.payloadUrl" style="max-width: 240px; border-radius: 6px" />
                </template>
                <template v-else-if="msg.msgType === 'file'">
                  <div
                    class="file-card"
                    style="display: flex; flex-direction: column; align-items: flex-start; gap: 8px"
                  >
                    <div class="file-row" style="display: flex; align-items: center; gap: 12px">
                      <img
                        class="file-thumb"
                        src="@/assets/fileImage.jpg"
                        alt="file"
                        style="width: 80px; height: auto; border-radius: 6px"
                      />
                      <el-button
                        :icon="Download"
                        size="small"
                        circle
                        @click="downloadFile(msg.payloadUrl, msg.content)"
                      />
                      <el-button
                        :icon="TopRight"
                        size="small"
                        circle
                        @click="lookloadFile(msg.payloadUrl, msg.content)"
                      />
                    </div>
                    <div class="file-name" style="font-size: 12px; color: #555">
                      {{ msg.content }}
                      <!-- {{ (urlDecode(msg.payloadUrl) || '').split('\\').pop() }} -->
                    </div>
                  </div>
                </template>
                <template v-else> {{ msg.msgType }}: {{ msg.payloadUrl || msg.content }} </template>
              </div>
              <div class="message-time">{{ formatTime(msg.createdAt) }}</div>
            </div>
          </div>
        </div>

        <div class="chat-input-area">
          <div class="input-tools">
            <el-button class="tool-btn" title="图片" size="small" circle @click="pickImage">
              <el-icon><Picture /></el-icon>
            </el-button>
            <el-button class="tool-btn" title="文件" size="small" circle @click="pickFile">
              <el-icon><Folder /></el-icon>
            </el-button>
            <input ref="fileInput" type="file" style="display: none" @change="handleFileChange" />
          </div>
          <textarea
            class="message-input"
            placeholder="输入消息..."
            v-model="state.inputText"
            @keydown.ctrl.enter.prevent="sendText"
          ></textarea>
          <div class="input-actions">
            <button class="send-btn" :disabled="!canSend" @click="sendText">发送</button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 登录 弹窗 -->
  <el-dialog v-model="loginModal" title="登录" width="420px" align-center @close="closeLogin">
    <div class="form-grid">
      <label class="field">
        <span class="k">账号</span>
        <input v-model="loginForm.account" placeholder="请输入账号" />
      </label>
      <label class="field">
        <span class="k">密码</span>
        <input v-model="loginForm.passwordHash" type="password" placeholder="请输入密码" />
      </label>
    </div>
    <template #footer>
      <div class="dialog-footer" style="display: flex; gap: 8px; justify-content: flex-end">
        <el-button @click="closeLogin">取消</el-button>
        <el-button type="primary" @click="doLogin">登录</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 用户选择 弹窗 -->
  <el-dialog
    v-model="userPickerVisible"
    title="选择用户"
    width="520px"
    align-center
    destroy-on-close
  >
    <div style="display: flex; gap: 8px; margin-bottom: 12px">
      <el-input
        v-model="userSearch"
        placeholder="按账号搜索"
        clearable
        style="flex: 1"
        @keyup.enter="handleUserSearch"
      />
      <el-button type="primary" @click="handleUserSearch">搜索</el-button>
    </div>

    <div v-loading="userLoading" style="max-height: 420px; overflow: auto">
      <div
        v-for="u in userList"
        :key="u.id"
        style="
          display: flex;
          align-items: center;
          padding: 8px 6px;
          border-bottom: 1px solid #f0f0f0;
        "
      >
        <el-avatar :src="u.avatarUrl" size="small" style="margin-right: 10px" />
        <div style="flex: 1; min-width: 0">
          <div
            style="
              font-size: 13px;
              font-weight: 500;
              color: #333;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            "
          >
            {{ u.account }}
          </div>
          <div
            style="
              font-size: 12px;
              color: #888;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            "
          >
            昵称：{{ u.nickname || '-' }}
          </div>
        </div>
        <el-tag :type="u.status === 1 ? 'success' : 'info'" size="small" style="margin-right: 10px">
          {{ u.status === 1 ? '正常' : '停用' }}
        </el-tag>
        <el-button size="small" type="primary" @click="addUserFromList(u)">添加</el-button>
      </div>

      <div
        v-if="!userLoading && userList.length === 0"
        style="padding: 12px; text-align: center; color: #999; font-size: 12px"
      >
        暂无数据
      </div>
    </div>

    <template #footer>
      <div style="display: flex; justify-content: space-between; align-items: center; width: 100%">
        <div style="font-size: 12px; color: #999">共 {{ userTotal }} 条</div>
        <el-pagination
          :current-page="userPage"
          :page-size="userPageSize"
          :total="userTotal"
          layout="prev, pager, next, sizes"
          :page-sizes="[10, 20, 30, 50]"
          small
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </template>
  </el-dialog>

  <!-- 删除会话 弹窗 -->
  <el-dialog
    v-model="delDialogVisible"
    title="删除会话"
    width="520px"
    align-center
    destroy-on-close
  >
    <div style="margin-bottom: 8px; font-size: 12px; color: #888">当前用户参与的会话列表</div>

    <div v-loading="delLoading" style="max-height: 420px; overflow: auto">
      <div
        v-for="s in delSessions"
        :key="s.id"
        style="
          display: flex;
          align-items: center;
          padding: 8px 6px;
          border-bottom: 1px solid #f0f0f0;
        "
      >
        <el-avatar
          :src="
            s.sessionType === 'group' ? groupAvatar : s.sysUserVo?.avatarUrl || userAvatar.value
          "
          size="small"
          style="margin-right: 10px"
        />
        <div style="flex: 1; min-width: 0">
          <div
            style="
              font-size: 13px;
              font-weight: 500;
              color: #333;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            "
          >
            {{ s.sessionType === 'group' ? s.name || '群聊' : s.sysUserVo?.account || '单聊' }}
          </div>
          <div
            style="
              font-size: 12px;
              color: #888;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            "
          >
            会话ID：{{ s.id }}
          </div>
        </div>
        <el-button size="small" type="danger" @click="deleteSessionItem(s.id)">删除会话</el-button>
      </div>

      <div
        v-if="!delLoading && delSessions.length === 0"
        style="padding: 12px; text-align: center; color: #999; font-size: 12px"
      >
        暂无会话
      </div>
    </div>

    <template #footer>
      <div style="display: flex; justify-content: flex-end; width: 100%">
        <el-button @click="delDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  UserFilled,
  Picture,
  Folder,
  Refresh,
  Setting,
  Download,
  ZoomIn,
  ZoomOut,
  Sunny,
  Moon,
  TopRight,
} from '@element-plus/icons-vue'
import { loginUser, getKeepAlive, getOnlineInfo } from '@/api/chat/user'
import { pageSysUsers, type SysUser, type BoPage, type SysUserPageParams } from '@/api/chat/user'

const myAvatar = ref('https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg')
const loginModal = ref(false)
const loginId = ref(0)
const loginForm = reactive({ account: '', passwordHash: '' })
function openLogin() {
  loginForm.account = ''
  loginForm.passwordHash = ''
  loginModal.value = true
}
function closeLogin() {
  loginModal.value = false
}
async function doLogin() {
  if (!loginForm.account) {
    ElMessage.warning('请输入账号')
    return
  }
  if (!loginForm.passwordHash) {
    ElMessage.warning('请输入密码')
    return
  }
  try {
    const res = await loginUser({
      account: loginForm.account,
      passwordHash: loginForm.passwordHash,
    })
    const token = res?.data?.data?.token ?? res?.data?.token ?? res?.data?.data?.jwt
    if (token) {
      localStorage.setItem('token', String(token))
      localStorage.setItem('sysUser', JSON.stringify(res?.data?.data ?? res?.data))
      myAvatar.value = res?.data?.data?.avatarUrl
      loginId.value = res?.data?.data?.id ?? res?.data?.id ?? res?.data?.data?.userId
      ElMessage.success('登录成功')
      getKeepAlive({ userId: loginId.value })
      closeLogin()
    } else {
      ElMessage.error('登录失败：未返回 token')
    }
  } catch {
    ElMessage.error('登录失败')
  }
}

import {
  listMySessions,
  createSingleSession,
  listSessionMembers,
  type ChatSession,
  deleteSingle,
} from '@/api/chat/session'
import { getMessageHistory, sendMessage, type ChatMessage } from '@/api/chat/message'
import { uploadFile } from '@/api/chat/file'

import mqtt, { type MqttClient } from 'mqtt'

const mqttClient = ref<MqttClient | null>(null)
// topic -> handler 映射
const mqttHandlers = new Map<string, (payload: Uint8Array | string, topic: string) => void>()

function initMqttClient() {
  if (mqttClient.value) return mqttClient.value
  const url = import.meta.env.VITE_APP_WEBSOCKET_URL || 'ws://127.0.0.1:8033'
  try {
    const client = mqtt.connect(url, {
      // 如需鉴权可在此补充 username/password/clientId 等
      reconnectPeriod: 3000,
    })
    client.on('connect', () => {
      console.log('[MQTT] connected', url)
    })
    client.on('reconnect', () => {
      console.log('[MQTT] reconnecting...')
    })
    client.on('error', (err) => {
      console.error('[MQTT] error', err)
    })
    client.on('message', (topic, payload) => {
      const handler = mqttHandlers.get(topic)
      if (handler) {
        handler(payload, topic)
      } else {
        // 未注册处理器的消息可按需记录
        // console.log('[MQTT] message (unhandled)', topic, payload?.toString?.())
      }
    })
    mqttClient.value = client
    return client
  } catch (e) {
    console.error('[MQTT] connect failed', e)
    return null
  }
}

/**
 * 订阅指定主题，并使用 handler 处理消息
 * @param topic 主题，如 'chat/123'
 * @param handler 回调 (payload, topic) => void
 */
function subscribeToTopic(
  topic: string,
  handler: (payload: Uint8Array | string, topic: string) => void,
) {
  const client = initMqttClient()
  if (!client) {
    ElMessage.error('MQTT 客户端未初始化')
    return
  }
  mqttHandlers.set(topic, handler)
  client.subscribe(topic, (err: Error | null) => {
    if (err) {
      console.error('[MQTT] subscribe error', topic, err)
      ElMessage.error('订阅失败：' + topic)
    } else {
      console.log('[MQTT] subscribed', topic)
    }
  })
}

function handleMqttMesssage(payload: Uint8Array | string, topic: string) {
  const currentTopic = 'chat/group/' + state.activeSessionId + '/channel'
  if (topic == currentTopic) {
    state.messages.push(JSON.parse(payload.toString()))
  }
}

// 可选：提供一个取消订阅的封装
function unsubscribeTopic(topic: string) {
  const client = mqttClient.value
  if (!client) return
  client.unsubscribe(topic, (err: Error | null) => {
    if (err) {
      console.error('[MQTT] unsubscribe error', topic, err)
    } else {
      mqttHandlers.delete(topic)
      console.log('[MQTT] unsubscribed', topic)
    }
  })
}

const groupAvatar =
  'https://images.unsplash.com/photo-1517245386807-bb43f82c33c4?auto=format&fit=crop&w=200&q=80'
const userAvatar = ref(
  'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?auto=format&fit=crop&w=200&q=80',
)
const selfAvatar = computed(() => myAvatar.value)
const otherAvatar = ref(userAvatar.value)

/** 消息容器与滚动到底部 */
const chatMessagesRef = ref<HTMLDivElement | null>(null)
function scrollToBottom() {
  // 使用微任务，确保 DOM 已更新后再滚动
  Promise.resolve().then(() => {
    const el = chatMessagesRef.value
    if (el) el.scrollTop = el.scrollHeight
  })
}

const state = reactive({
  userIdInput: '' as any,
  currentUserId: 0,
  sessions: [] as ChatSession[],
  activeSessionId: 0 as number,
  activeSessionType: 'single' as 'single' | 'group',
  messages: [] as ChatMessage[],
  page: 1,
  size: 30,
  inputText: '',
  pendingUploadUrl: '' as string | null,
})

const headerTitle = computed(() => {
  if (!state.activeSessionId) return '未选择会话'
  const s = state.sessions.find((x) => x.id === state.activeSessionId)
  return s?.sysUserVo?.account || (state.activeSessionType === 'group' ? '群聊' : '单聊')
})

const headerAvatar = computed(() =>
  state.activeSessionType === 'group' ? groupAvatar : userAvatar.value,
)

onMounted(() => {
  loginId.value = getLoginId()
  fetchSessions()
})

// 保活定时器：每 9000ms 调用一次，不处理返回
let keepAliveTimer: any = null
onMounted(() => {
  const token = localStorage.getItem('token')
  if (token && !keepAliveTimer) {
    keepAliveTimer = setInterval(async () => {
      try {
        if (getLoginId() > 0) {
          const res = await getKeepAlive({ userId: getLoginId() })
          if (res?.data?.code != 0) {
            loginId.value = 0
          } else {
            loginId.value = getLoginId()
          }
        }
      } catch {}
    }, 60000)
  }
})
onUnmounted(() => {
  if (keepAliveTimer) {
    clearInterval(keepAliveTimer)
    keepAliveTimer = null
  }
  if (mqttClient.value) {
    try {
      mqttClient.value.end(true)
    } catch {}
    mqttClient.value = null
  }
})

function formatTime(t?: string) {
  if (!t) return ''
  try {
    const d = new Date(t)
    return `${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`
  } catch {
    return t
  }
}

async function applyUserId() {
  const idNum = Number(state.userIdInput)
  if (!idNum || idNum <= 0) {
    return alert('请输入有效的用户ID')
  }
  if (!idNum || getLoginId() <= 0) {
    return alert('请登录')
  }
  state.currentUserId = idNum

  addUserId(idNum)
}

async function addUserId(idNum: number) {
  if (!idNum || getLoginId() <= 0) {
    return alert('请登录')
  }
  try {
    await createSingleSession({ userA: getLoginId(), userB: idNum })
  } catch (e) {
    // 创建已存在或失败时忽略错误
  }
  await fetchSessions()
}

async function fetchSessions() {
  if (getLoginId() <= 0) {
    return
  }
  const res = await listMySessions({ userId: getLoginId() })
  state.sessions = res?.data?.data || []
  // 自动选择第一个会话
  if (state.sessions.length) {
    selectSession(state.sessions[0])
  } else {
    state.activeSessionId = 0
    state.messages = []
  }
}

function urlDecode(url?: string | null) {
  if (!url) {
    ElMessage.warning('文件地址无效')
    return
  }
  const duc = decodeURIComponent(url)
  return duc
}

async function selectSession(session: ChatSession) {
  state.activeSessionId = session.id
  state.activeSessionType = session.sessionType
  state.page = 1
  otherAvatar.value = session.sysUserVo?.avatarUrl ?? userAvatar.value
  userAvatar.value = session.sysUserVo?.avatarUrl ?? userAvatar.value

  if (session.sessionType === 'single') {
    subscribeToTopic('chat/group/' + session.id + '/channel', handleMqttMesssage)
  }

  await fetchMessages(true)
  await fetchSessionMembers()
}

async function fetchMessages(reset = false) {
  if (!state.activeSessionId) return
  const res = await getMessageHistory({
    sessionId: state.activeSessionId,
    page: state.page,
    size: state.size,
  })
  const list: ChatMessage[] = res?.data?.data || []
  // 历史按 createdAt 倒序；在 UI 中保持时间顺序展示
  const ordered = [...list].reverse()
  state.messages = reset ? ordered : [...ordered, ...state.messages]
  scrollToBottom()
}

async function fetchSessionMembers() {
  if (!state.activeSessionId) return
  if (!state.activeSessionId) return
  const res = await listSessionMembers(state.activeSessionId)
  const list = res?.data?.data || []

  for (let i = 0; i < list.length; i++) {
    const member = list[i]
    if (member.userId === loginId.value) {
      continue
    }
    state.currentUserId = member.userId
    break
  }
}

async function refreshActiveMessages() {
  await fetchMessages(true)
}

const canSend = computed(
  () =>
    !!state.activeSessionId &&
    !!state.currentUserId &&
    (!!state.inputText || !!state.pendingUploadUrl),
)

async function refreshMessages() {
  fetchSessions()
}

/** 用户选择弹窗状态与逻辑 */
const userPickerVisible = ref(false)
const userSearch = ref('')
const userList = ref<SysUser[]>([])
const userPage = ref(1)
const userPageSize = ref(10)
const userTotal = ref(0)
const userLoading = ref(false)

function openUserPicker() {
  userPickerVisible.value = true
  userPage.value = 1
  fetchUserPage()
}

async function fetchUserPage() {
  userLoading.value = true
  try {
    const params: SysUserPageParams = {
      account: userSearch.value?.trim() || undefined,
      pageNum: userPage.value,
      pageSize: userPageSize.value,
    }
    const res = await pageSysUsers(params)
    const data = (res?.data?.data || res?.data) as BoPage<SysUser> | undefined
    userList.value = data?.list || []
    userTotal.value = data?.total || 0
  } catch {
    userList.value = []
    userTotal.value = 0
  } finally {
    userLoading.value = false
  }
}

function handleUserSearch() {
  userPage.value = 1
  fetchUserPage()
}
function handlePageChange(p: number) {
  userPage.value = p
  fetchUserPage()
}
function handleSizeChange(s: number) {
  userPageSize.value = s
  userPage.value = 1
  fetchUserPage()
}

async function addUserFromList(u: SysUser) {
  if (!u?.id) return
  await addUserId(u.id)
  ElMessage.success('已添加到会话')
  userPickerVisible.value = false
}

/** 打开用户选择弹窗 */
async function addUserClick() {
  openUserPicker()
}

/** 删除会话 弹窗状态与逻辑 */
const delDialogVisible = ref(false)
const delSessions = ref<ChatSession[]>([])
const delLoading = ref(false)

async function delUserClick() {
  openDelDialog()
}

function openDelDialog() {
  delDialogVisible.value = true
  fetchDelSessions()
}

async function fetchDelSessions() {
  delLoading.value = true
  try {
    const res = await listMySessions({ userId: getLoginId() })
    delSessions.value = res?.data?.data || []
  } catch {
    delSessions.value = []
  } finally {
    delLoading.value = false
  }
}

function getLoginId() {
  const raw = localStorage.getItem('sysUser')
  if (raw) {
    try {
      const obj = JSON.parse(raw)
      myAvatar.value = obj.avatarUrl
      return obj.id
    } catch {
      console.log('sysUser not valid JSON')
    }
  } else {
    console.log('sysUser not found in localStorage')
  }

  return 0
}

async function deleteSessionItem(sessionId: number) {
  if (!sessionId) return
  try {
    // 后端文档为 { sessionId }，当前 API 类型为 { userId }，按实现传入 sessionId
    const res = await deleteSingle({ sessionId: sessionId } as any)
    if ((res?.data?.code ?? res?.code) === 0) {
      ElMessage.success('已删除会话')
      await fetchSessions()
      delDialogVisible.value = false
    } else {
      ElMessage.error('删除失败')
    }
  } catch {
    ElMessage.error('删除失败')
  }
}

async function settingClick() {
  console.log('setting', '点击了设置')
}

async function sendText() {
  if (!canSend.value) return

  const pu = state.pendingUploadUrl
  const imageExts = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg']

  let msgType: string = 'text'
  let content: string | undefined = state.inputText
  let payloadUrl: string | undefined = undefined

  if (pu !== null && pu !== undefined) {
    if (pu === '') {
      // 空字符 => txt
      msgType = 'text'
      payloadUrl = undefined
      // content 保持文本
    } else {
      // 非空字符串：按后缀判断 image 或 file
      const lower = (urlDecode(pu) || '').toLowerCase()
      const lowerName = (lower.split('\\').pop() || '').trim()
      const ext = (lowerName.split('.').pop() || '').trim()
      msgType = imageExts.includes(ext) ? 'image' : 'file'
      payloadUrl = pu
      content = state.inputText
    }
  } else {
    // 未提供上传地址 => 普通文本
    msgType = 'text'
    payloadUrl = undefined
  }

  const body: ChatMessage = {
    senderId: state.currentUserId,
    sessionId: state.activeSessionId,
    msgType,
    content,
    payloadUrl,
  }
  const res = await sendMessage({ targetSessionId: state.activeSessionId }, body)
  if (res?.data?.code === 0) {
    // 发送后刷新最新消息
    state.inputText = ''
    state.pendingUploadUrl = null
    await refreshActiveMessages()
  } else {
    alert('发送失败')
  }
}

// 上传图片/文件并作为消息发送（示例：图片）
const fileInput = ref<HTMLInputElement | null>(null)
function pickImage() {
  fileInput.value?.setAttribute('accept', 'image/*')
  fileInput.value?.click()
}
function pickFile() {
  fileInput.value?.removeAttribute('accept')
  fileInput.value?.click()
}

function downloadFile(url?: string | null, filename?: string) {
  if (!url) {
    ElMessage.warning('文件地址无效')
    return
  }
  const finalUrl = url.replace('downloadFile', 'download')
  try {
    fetch(finalUrl)
      .then((res) => res.blob())
      .then((blob) => {
        const urlB = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = urlB
        a.download = filename || ''
        a.click()
        URL.revokeObjectURL(urlB)
      })

    // const a = document.createElement('a')
    // a.href = url
    // console.log(a, 'filename a')
    // a.download = filename || ''
    // a.target = '_blank'
    // document.body.appendChild(a)
    // a.click()
    // document.body.removeChild(a)
  } catch (e) {
    ElMessage.error('下载失败')
  }
}

function lookloadFile(url?: string | null, filename?: string) {
  if (!url) {
    ElMessage.warning('文件地址无效')
    return
  }
  try {
    const a = document.createElement('a')
    a.href = url
    console.log(a, 'filename a')
    a.target = '_blank'
    a.click()
  } catch (e) {
    ElMessage.error('下载失败')
  }
}

async function handleFileChange(e: Event) {
  console.log('handleFileChange', e)
  const el = e.target as HTMLInputElement
  const file = el.files?.[0]
  if (!file) return
  console.log('file', file)
  const res = await uploadFile(file)
  const url = res?.data?.data
  if (url) {
    state.pendingUploadUrl = url
    state.inputText = file.name
    // 直接发送图片消息
    await sendText()
  } else {
    alert('上传失败')
  }
  el.value = ''
}
</script>

<style scoped>
* {
  margin: 0;
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
}
.app {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 90vh;
}
.wechat-container {
  display: flex;
  width: 1000px;
  height: 700px;
  background-color: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  position: relative;
}
.sidebar {
  width: 65px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 0;
}
.nav-item {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6px;
  cursor: pointer;
  color: #7d7d7d;
  transition: all 0.2s;
  position: relative;
}
.chat-online {
  font-size: 12px;
  color: #9b9b9b;
  margin-top: 2px;
}

.set-item {
  width: 100%;
  position: absolute;
  bottom: 0;
}
.nav-item.active {
  color: #07c160;
}
.nav-item:hover:not(.active) {
  background-color: #dad6d6;
}
.nav-item i {
  font-size: 20px;
}

.contact-panel {
  width: 230px;
  border-right: 1px solid #d8d8d8;
  display: flex;
  flex-direction: column;
}
.search-bar {
  background: #fbfbfb;
  padding: 15px 10px;
  display: flex;
  align-items: center;
}
.search-box {
  background-color: #e6e6e6;
  border-radius: 4px;
  padding: 1px 12px;
  display: flex;
  align-items: center;
  position: relative;
}
.search-add {
  margin-left: 10px;
  cursor: pointer;
}
.search-box i {
  color: #9b9b9b;
  font-size: 14px;
  margin-right: 6px;
}
.search-box input {
  background: transparent;
  border: none;
  color: #333;
  width: 100%;
  outline: none;
  font-size: 12px;
  padding: 4px 0;
}

.contact-list {
  flex: 1;
  overflow-y: auto;
  background-color: #fbfbfb;
}
.contact-item {
  display: flex;
  height: 65px;
  align-items: center;
  padding: 10px 15px;
  cursor: pointer;
}
.contact-item:hover {
  background-color: #f5f5f5;
}
.contact-item.active {
  background-color: #e8f5e9;
}
.contact-avatar {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  position: relative;
}
.contact-info {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-align: left;
}
.contact-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}
.contact-preview {
  font-size: 12px;
  color: #7d7d7d;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}
.contact-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  flex-shrink: 0;
}
.contact-time {
  font-size: 11px;
  color: #9b9b9b;
  margin-bottom: 4px;
}
.unread-count {
  color: white;
  font-size: 11px;
  min-width: 18px;
  height: 18px;
  border-radius: 9px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f0f0f0;
}
.chat-header {
  padding: 12px 16px;
  background-color: #ededed;
  border-bottom: 1px solid #d4d4d4;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.chat-title {
  display: flex;
  align-items: center;
}
.chat-avatar {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  position: relative;
}
.chat-name {
  font-weight: 500;
  font-size: 16px;
  color: #333;
}
.chat-status {
  font-size: 12px;
  color: #9b9b9b;
  margin-top: 2px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  /* 隐藏滚动条但保留滚动 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
}
.chat-messages::-webkit-scrollbar {
  width: 0;
  height: 0;
}
.message {
  display: flex;
  margin-bottom: 20px;
}
.message.self {
  flex-direction: row-reverse;
}
.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  margin: 0 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  flex-shrink: 0;
}
.message-content {
  max-width: 65%;
  position: relative;
}
.message-bubble {
  padding: 10px 14px;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
}
.message.other .message-bubble {
  background-color: #ffffff;
  border: 1px solid #e6e6e6;
  margin-left: 10px;
}
.message.self .message-bubble {
  background-color: #9eea6a;
  color: #333;
  margin-right: 10px;
}
.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: center;
}
.message.self .message-time {
  text-align: right;
  padding-right: 15px;
}
.message.other .message-time {
  text-align: left;
  padding-left: 15px;
}
.timestamp {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin: 15px 0;
}

.chat-input-area {
  padding: 15px;
  background-color: #f5f5f5;
  border-top: 1px solid #e0e0e0;
  position: relative;
}
.input-tools {
  display: flex;
  padding: 5px 0;
  margin-bottom: 10px;
}
.tool-btn {
  width: 30px;
  height: 30px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #7d7d7d;
  cursor: pointer;
  margin-right: 8px;
  transition: all 0.2s;
}
.tool-btn:hover {
  background-color: #e0e0e0;
  color: #333;
}
.message-input {
  width: 100%;
  height: 100px;
  padding: 12px;
  resize: none;
  font-size: 14px;
  transition: border-color 0.2s;
  border: none;
  background: none;
  outline: none;
}
.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.send-btn {
  padding: 5px 30px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}
.send-btn:hover {
  background-color: #06ad56;
}
.send-btn:active {
  background-color: #059a4c;
}

.empty-tip {
  font-size: 12px;
  color: #9b9b9b;
  padding: 12px;
  text-align: center;
}
</style>
<style scoped>
.xwchat-login-btn {
  position: fixed;
  top: 12px;
  right: 12px;
  z-index: 3000;
}
.icon-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  background: #fff;
  color: #111827;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
.icon-btn:hover {
  background: #f8fafc;
}

/* 登录弹窗表单行样式：标签与输入框同一行，并左右对齐 */
.form-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
}
.form-grid .field {
  display: flex;
  align-items: center;
  gap: 12px;
}
.form-grid .field .k {
  display: inline-block;
  width: 64px;
  text-align: right;
  color: #6b7280;
  font-size: 12px;
}
.form-grid .field input {
  flex: 1;
  padding: 8px 10px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  outline: none;
}
.form-grid .field input:focus {
  border-color: #2563eb;
}

/* 移动端适配修正：容器占满视口高度，内部区域滚动，避免整体页面被撑高 */
@media (max-width: 768px) {
  .app {
    align-items: center;
    min-height: 100vh;
    padding-bottom: env(safe-area-inset-bottom, 0);
  }
  .wechat-container {
    width: 100%;
    height: 100vh;
    max-width: 100%;
    max-height: 100vh;
    overflow: hidden; /* 不让整体高度被内容撑大 */
    border-radius: 0;
    box-shadow: none;
  }
  .contact-list,
  .chat-messages {
    -webkit-overflow-scrolling: touch; /* iOS 惯性滚动 */
  }
}
</style>
<style scoped>
/* 强制消息文本自动换行，避免超出右侧 */
.message-content { min-width: 0; }
.message-bubble {
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-wrap: anywhere;
}
</style>
